package com.briup.myblog.aop;

import com.briup.myblog.bean.basic.BaseLog;
import com.briup.myblog.dao.basic.BaseLogMapper;
import com.briup.myblog.utils.JwtUtil;
import com.briup.myblog.utils.Result;
import com.briup.myblog.utils.UserInfoUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private BaseLogMapper logMapper;
    @Pointcut("execution(* com.briup.myblog.web.controller.LoginController.login(..))")
    public void loginPointCut(){
        //当执行登录操作时，可以实现日志记录
        //短信平台。实现将用户登录消息告诉用户137.........

    }



    //定义需要提供前置通知的方法的切入点规则
    @Pointcut("execution(* com.briup.myblog.web.controller.*.*(..)) && @annotation(Logging) ")
    public void LogPointCut(){

    }
    //请求的路径必须是auth路径下的接口方法
    @Before("LogPointCut()")
    public void logAdvice(){
        //获取到用户的请求信息及个人信息
        Map<String, Object> userInfo = UserInfoUtil.getUserInfo();
        //将获取到的信息保存在日志表中
        BaseLog baseLog = BaseLog.builder()
                .logUsername((String) userInfo.get("username"))
                .logRealname((String) userInfo.get("realname"))
                .logRequestMethod((String) userInfo.get("method"))
                .logRequestUri((String) userInfo.get("url"))
                .logTime(new Date())
                .build();
        logMapper.insert(baseLog);
    }
    @Around("loginPointCut()")
    public Object LoginAdivce(ProceedingJoinPoint pjp) throws Throwable{
        //1只有在用户登录成功再进行日志记录
        //获取方法的返回值
        Object obj = pjp.proceed();
        //2.通过返回值类型获取用户信息token
        String token = (String) ((Result) obj).getData();
        Map<String, Object> userInfo = JwtUtil.getInfo(token);
        //获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        BaseLog baseLog = BaseLog.builder()
                .logUsername((String) userInfo.get("username"))
                .logRealname((String) userInfo.get("realname"))
                .logTime(new Date())
                .logRequestUri(request.getRequestURI())
                .logRequestMethod(request.getMethod())
                .build();
        logMapper.insert(baseLog);
        return obj;
    }
}